package com.feijia.aijingjingus;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Location;
import android.magictools.cn.frameanimationdrawable.FrameByFrameAnimationDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.clj.fastble.BleManager;
import com.clj.fastble.conn.BleCharacterCallback;
import com.clj.fastble.conn.BleGattCallback;
import com.clj.fastble.data.ScanResult;
import com.clj.fastble.exception.BleException;
import com.feijia.aijingjingus.util.PreferencesUtils;
import com.feijia.aijingjingus.view.Dialog;
import com.feijia.aijingjingus.view.CircleImageView;
import com.feijia.aijingjingus.view.CircleLayout;
import com.junkchen.blelib.BleService;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;

import java.util.List;

import io.nlopez.smartlocation.OnLocationUpdatedListener;
import io.nlopez.smartlocation.OnReverseGeocodingListener;
import io.nlopez.smartlocation.SmartLocation;
import io.nlopez.smartlocation.location.providers.LocationGooglePlayServicesProvider;


import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP;
import static com.feijia.aijingjingus.GlobalHelper.*;
import static com.feijia.aijingjingus.GlobalHelper.FirstDay;
import static com.feijia.aijingjingus.GlobalHelper.LastDay;
import static com.feijia.aijingjingus.GlobalHelper.NickName;
import static com.feijia.aijingjingus.GlobalHelper.Temperature;

public class controlCenterActivity extends AppCompatActivity implements CircleLayout.OnItemClickListener,CircleLayout.OnItemSelectedListener{
    ImageButton imageButton5;
    TextView textView5;
    Dialog dialog;
    TextView tvStartDetection,textView20;
    Button btStartDetection;
    FrameLayout frameLayout;
    RelativeLayout relativeLControlCenter;
    RelativeLayout relativeLayout;
    LinearLayout linearLayout3;
    CircleLayout circleLayout;
    EditText etNickName;
    EditText etFirstDay, etLastDay;
    EditText etMenstruation;
    EditText etAge;
    Button startDetection;
    //String NickName, FirstDay, LastDay;
    DrawHookView DHV1, DHV2;
    int Age, Menstruation, AniMode = 0;
    final long animTime = 1000;
    OptionsPickerView pvNickName, pvAge, pvMenstruation, pvPeriod, pvWelcome, pvWelcomeend,pvRawDetectionData,pvChooseSex;
    TimePickerView pvFirstDay;
    LoadingDialog ld;

    private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
    Context context = this;
    FrameByFrameAnimationDrawable FAD, FAD2;
    AnimatorSet set, set2, set3, set4, guideAniSet, playingGuideAniSet;
    private SharedPreferences sp;
    private boolean PlayedGuide = false;

    //public LocationClient mLocationClient = null;
    //public BDLocationListener myListener = new MyLocationListener();
    int width, height, densityDpi;
    float density;
    boolean isGuideAniInit = false;
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    private Handler dialogHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {
                //这里增加对case 1和2的处理
                case 1:
//                  蓝牙连接意外断开，正在重连... 弹窗提示
                    dialog=new Dialog(controlCenterActivity.this,Constants.BLE_INTERRUPUT);
                    dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
                    dialog.show();
                    break;
                case 2:
                    dialog=new Dialog(controlCenterActivity.this,Constants.BLE_UNOPEN);
                    dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
                    dialog.show();
                    break;

            }
        }
    };

    Runnable UpdateOp = new Runnable() {
        @Override
        public void run() {
            JSONObject root = new JSONObject();
            SharedPreferences.Editor editor = sp.edit();
            try {
                root.put("UserNo", Long.parseLong(GUserNum));
                if (!NickName.isEmpty()) {
                    root.put("UserNickname", NickName);
                    editor.putString("NickName", NickName);
                }
                if (Age != 0) {
                    root.put("Age", Age);
                    editor.putInt("Age", Age);
                }
                root.put("Sex", Sex);
                editor.putInt("Sex", Sex);
                if (!FirstDay.isEmpty()) {
                    root.put("StartDay", FirstDay);
                    editor.putString("FirstDay", FirstDay);
                }
                /*
                if (!LastDay.isEmpty()) {
                    root.put("EndDay", LastDay);
                    editor.putString("LastDay", LastDay);
                }*/
                if (Menstruation != 0) {
                    root.put("Menstruation", Menstruation);
                    editor.putInt("Menstruation", Menstruation);
                }
                if (PeriodLength != 0) {
                    root.put("PeriodLength", PeriodLength);
                    editor.putInt("PeriodLength", PeriodLength);
                }
                editor.apply();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            JSONObject out = GlobalHelper.PostData(root, "http://120.77.255.57/ting/updateUser.php");
            System.out.println(out.toString());
            /*  //操作结果
            String tempstr = null;
            try {
                tempstr = out.get("OperateResult").toString();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            final String Resultcode = tempstr;
            handler.post(new Runnable() {
                @Override
                public void run() {
                    if (Resultcode != null && Resultcode.compareTo("1") >= 0) {

                        //Toast.makeText(getApplicationContext(), context.getString(R.string.modifySuccessfully),
                        //        Toast.LENGTH_SHORT).show();

                    } else {
                        //Toast.makeText(getApplicationContext(), context.getString(R.string.modifyUnsuccessfully),
                        //        Toast.LENGTH_SHORT).show();
                    }
                }
            });
            */
        }
    };
    int scanCount = 0;

    Runnable CheckNet = new Runnable() {
        @Override
        public void run() {
            while (isCheckingNet)
            {
                //isNetOut = !mNetworkInfo.isAvailable();
                isNetOut = isPingSuccess(3,"120.77.255.57")!=0;
                System.out.println("Net S:"+isNetOut);
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            isCheckingNet=false;
        }
    };

    BleGattCallback BleCallback = new BleGattCallback() {
        @Override
        public void onFoundDevice(ScanResult scanResult) {
            System.out.println("Ble找到设备");
            //isBleRescanThreadRunning=false;
        }

        @Override
        public void onConnecting(BluetoothGatt gatt, int status) {
            System.out.println("Ble正在连接设备");
        }

        @Override
        public void onConnectError(BleException exception) {
            System.out.println("Ble连接错误" + exception.toString());
            if (exception.getCode() == 103) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        //bleManager.closeBluetoothGatt();
                    }
                });

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //bleManager = null;
                //bleManager = new BleManager(context);
                handler.post(new Runnable() {
                    @Override
                    public void run() {

                        bleManager.enableBluetooth();
                        if (!bleManager.isInScanning())
                            bleManager.scanNameAndConnect("Nordic_Chen", BleScanTime, true, BleCallback);
                    }
                });
                ResetDetecting();
                BleOpDelay();
                Disconnect();
            }
        }

        @Override
        public void onConnectSuccess(BluetoothGatt gatt, int status) {
            System.out.println("Ble连接成功 Address:" + gatt.getDevice().getAddress());
            BleAddress = gatt.getDevice().getAddress();
            isBleRescanThreadRunning = false;
            DeviceName = gatt.getDevice().getName();
            BleOpDelay();
            Connect();
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            System.out.println("Ble发现服务");
            BleOpDelay();
            handler.post(new Runnable() {
                @Override
                public void run() {
                    setNotify();
                }
            });
        }

        /**
         * @param gatt
         * @param status
         * @param exception
         */
        @Override
        public void onDisConnected(BluetoothGatt gatt, int status, BleException exception) {
            System.out.println("Ble断开连接");
            BleOpDelay();
            isBleConnectingOrConnected = false;
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), context.getString(R.string.ReconnectBle),
                            Toast.LENGTH_SHORT).show();
                    dialogHandler.sendEmptyMessage(1);
                }
            });
            BleHandler.sendEmptyMessage(1);
            //bleManager = null;

//            Intent intent = getIntent();
//            finish();
//            startActivity(intent);



//            dialog=new Dialog(controlCenterActivity.this,"bleinterrupt");
//            dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
//            dialog.show();

/*
            handler.post(new Runnable() {
                @Override
                public void run() {
                    bleManager = new BleManager(context);
                    bleManager.enableBluetooth();
                    if (!bleManager.isInScanning())
                        bleManager.scanNameAndConnect("Nordic_Chen", BleScanTime, true, BleCallback);
                }
            });

            ResetDetecting();
            //bleManager.scanNameAndConnect("Nordic_Chen",30000,true,BleCallback);
            Disconnect();
*/
        }
    };

    @Override
    protected void onDestroy() {
        isNeedInitBle = false;
        super.onDestroy();
    }

    /*** @param savedInstanceState
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    @SuppressLint("ResourceType")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_control_center_layout);
//      性别男时修改UI背景色
//        if(PreferencesUtils.getString(getApplicationContext(),PreferencesUtils.PREFERENCE_NAME).equals("男")){
//            imageButton5=(ImageButton)findViewById(R.id.imageButton5);
//            textView20=(TextView)findViewById(R.id.textView20);
//            textView20.setTextColor(getColor(R.color.womain_pink));
//            imageButton5.setImageDrawable(getDrawable(R.drawable.detectionman));
//            btStartDetection=(Button)findViewById(R.id.StartDetection);
//            frameLayout=(FrameLayout)findViewById(R.id.flGuideBtn);
//            relativeLayout=(RelativeLayout)findViewById(R.id.relativeLayout);
//            frameLayout.setBackground(getDrawable(R.drawable.ripple_light_pink_rectangle_with_fake_shadow_two));
//            relativeLayout.setBackground(getDrawable(R.drawable.top_bar_with_shadow_two));
//            btStartDetection.setBackground(getDrawable(R.drawable.ripple_red_rectangle_with_shadow_two));
////            relativeLControlCenter=(RelativeLayout)findViewById(R.id.activity_control_center_layout);
////            relativeLControlCenter.setBackgroundColor(getColor(R.color.womain_pink));
//        }



        textView5=(TextView)findViewById(R.id.textView5);
        relativeLControlCenter=(RelativeLayout)findViewById(R.id.activity_control_center_layout);
        circleLayout=(CircleLayout)findViewById(R.id.circle_layout);
        circleLayout.setOnItemClickListener(this);
        circleLayout.setOnItemSelectedListener(this);
        tvStartDetection=(TextView)findViewById(R.id.tv_StartDetection);
        tvStartDetection.setText(((CircleImageView)circleLayout.getSelectedItem()).getName());



        handler = new Handler();
        context = this;
        isNeedInitBle = true;
        System.out.println("Ble Handler Reset");
        if(NetConnectivityManager==null)
        {
            NetConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
        }
        if(!isCheckingNet) {
            isCheckingNet = true;
            new Thread(CheckNet).start();
        }

        //SharedPreferences初始化
        sp = this.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        width = dm.widthPixels;         // 屏幕宽度（像素）
        height = dm.heightPixels;       // 屏幕高度（像素）
        density = dm.density;         // 屏幕密度（0.75 / 1.0 / 1.5）
        densityDpi = dm.densityDpi;     // 屏幕密度dpi（120 / 160 / 240）
        // 屏幕宽度算法:屏幕宽度（像素）/屏幕密度
        int screenWidth = (int) (width / density);  // 屏幕宽度(dp)
        int screenHeight = (int) (height / density);// 屏幕高度(dp)

        Log.d("h_bl", "屏幕宽度（像素）：" + width);
        Log.d("h_bl", "屏幕高度（像素）：" + height);
        Log.d("h_bl", "屏幕密度（0.75 / 1.0 / 1.5）：" + density);
        Log.d("h_bl", "屏幕密度dpi（120 / 160 / 240）：" + densityDpi);
        Log.d("h_bl", "屏幕宽度（dp）：" + screenWidth);
        Log.d("h_bl", "屏幕高度（dp）：" + screenHeight);


        //final ImageView bt1img = (ImageView) findViewById(R.id.ivBt1);
        final ImageView bt2img = (ImageView) findViewById(R.id.ivBt2);
        //final Animation alpha_anim = AnimationUtils.loadAnimation(this, R.anim.alpha_anim);
        final Animation alpha_anim_anti = AnimationUtils.loadAnimation(this, R.anim.alpha_anim_anti);
        TextView tvBT = (TextView) findViewById(R.id.tvBT);

        //alpha_anim.setDuration(animTime);
        alpha_anim_anti.setDuration(animTime);
        //bt1img.startAnimation(alpha_anim);
        bt2img.startAnimation(alpha_anim_anti);
        tvBT.startAnimation(alpha_anim_anti);


        //获取地理位置
        LocationGooglePlayServicesProvider provider = new LocationGooglePlayServicesProvider();
        provider.setCheckLocationSettings(true);

        SmartLocation.with(context).location(provider).start(new OnLocationUpdatedListener() {
            @Override
            public void onLocationUpdated(Location location) {
                System.out.println("Location:" + location.toString());
                SmartLocation.with(context).geocoding().reverse(location, new OnReverseGeocodingListener() {
                    @Override
                    public void onAddressResolved(Location location, List<Address> list) {
                        System.out.println("Location:" + location.toString());
                        for (Address i : list) {
                            System.out.println("Location:" + i.toString());
                        }
                        DetectionLocation = list.get(0).getLocality();
                    }
                });
                /*
                location.setLatitude(32.728444);
                location.setLongitude(-117.141474);
                SmartLocation.with(context).geocoding().reverse(location, new OnReverseGeocodingListener() {
                    @Override
                    public void onAddressResolved(Location location, List<Address> list) {
                        System.out.println("Location:" + location.toString());
                        for (Address i : list) {
                            System.out.println("Location:" + i.toString());
                        }
                        DetectionLocation = list.get(0).getLocality();
                    }
                });
                */
            }
        });


        //补登陆之后的上传数据
        System.out.println("NeedUploadDetection:" + NeedUploadDetection);
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (NeedUploadDetection && !GUserNum.isEmpty()) {
                    try {
                        NeedUploadDetectionData.put("UserNo", GUserNum);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    System.out.println("UploadDetection:" + NeedUploadDetectionData);
                    JSONObject out = GlobalHelper.PostData(NeedUploadDetectionData, "http://120.77.255.57/ting/insert" + DetectionType + ".php");
                    //多次重试
                    GlobalHelper.PostData(NeedUploadDetectionData, "http://120.77.255.57/ting/insert" + DetectionType + ".php");
                    GlobalHelper.PostData(NeedUploadDetectionData, "http://120.77.255.57/ting/insert" + DetectionType + ".php");
                    System.out.println("UploadDetection:" + out);
                    NeedUploadDetection = false;
                }
            }
        }).start();

        StartDetecting = false;
        BleReadCount = 0;


        //百度定位
        /*
        if(DetectionLocation.isEmpty()) {
            mLocationClient = new LocationClient(getApplicationContext());
            //声明LocationClient类
            mLocationClient.registerLocationListener(myListener);
            //注册监听函数
            LocationClientOption option = new LocationClientOption();
            option.setIsNeedAddress(true);
            option.setCoorType("WGS84");
            option.setLocationMode(LocationClientOption.LocationMode.Battery_Saving);
            mLocationClient.setLocOption(option);
            mLocationClient.start();
        }
        */
//        DHV1 = (DrawHookView) findViewById(R.id.DrawHookView1);
//        DHV2 = (DrawHookView) findViewById(R.id.DrawHookView2);
        DetectionType = "";


        etNickName = (EditText) findViewById(R.id.etNickName);
        etFirstDay = (EditText) findViewById(R.id.etFirstDay);
        etLastDay = (EditText) findViewById(R.id.etLastDay);
        etMenstruation = (EditText) findViewById(R.id.etMenstruation);
        etAge = (EditText) findViewById(R.id.etAge);
        if (GUserNum.equals(""))
            findViewById(R.id.linearLayout3).setVisibility(View.GONE);


        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                while (isNetOut);
                System.out.print("Ble before Init isNeedInitBle:"+isNeedInitBle);
                if(Sex!=1&&isNeedInitBle) {
                    System.out.print("Ble  Init");
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (bleManager == null)
                                bleManager = new BleManager(context);
                            if (mayRequestLocation()) {
                            }
//                        bleManager.enableBluetooth();

                        }
                    });


                    while (bleManager == null) ;
//                    bleManager.enableBluetooth();
                    if (!bleManager.isBlueEnable()){
                        dialogHandler.sendEmptyMessage(2);
                        BleOpDelay();
                    }
                    BleOpDelay();

                    if (!bleManager.isInScanning())
                        bleManager.scanNameAndConnect("Nordic_Chen", BleScanTime, true, BleCallback);

                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                        /*
                        if (!bleManager.isInScanning())
                            bleManager.scanNameAndConnect("Nordic_Chen", BleScanTime, true, BleCallback);
                        ResetDetecting();
                        */
                            ResetBleAndRescan();
                        }
                    });
                }
            }
        }).start();



        final BleCharacterCallback mBleCharacterCallback = new BleCharacterCallback() {
            @Override
            public void onSuccess(BluetoothGattCharacteristic characteristic) {
                System.out.println("Ble写入数据" + characteristic.getStringValue(0));
            }

            @Override
            public void onFailure(BleException exception) {
                System.out.println("Ble写入数据失败" + exception.toString());
            }

            @Override
            public void onInitiatedResult(boolean result) {
            }
        };


        if (!GUserNum.isEmpty()) {
            NickName = sp.getString("NickName", "");
            Age = sp.getInt("Age", 0);
            FirstDay = sp.getString("FirstDay", "");
            LastDay = sp.getString("LastDay", "");
            AssociatedUser = sp.getString("AssociatedUser", "");
            Menstruation = sp.getInt("Menstruation", 0);
            PeriodLength = sp.getInt("PeriodLength", 0);
            Sex = sp.getInt("Sex", 0);
            if(Sex == 1)
            {
                finish();
                Intent intent = new Intent("manMainActivity");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
            }
            if (NickName.isEmpty() || Age == 0 || FirstDay.isEmpty() || Menstruation == 0 || PeriodLength == 0) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        ld = new LoadingDialog(context);
                        ld.setLoadingText(" ")
                                .setSuccessText(" ")
                                .setFailedText(" ")
                                .setTextSize(0)
                                /*.setLoadingText(getString(R.string.Load_Data_str))
                                .setSuccessText(getString(R.string.Load_Data_Success_str))
                                .setFailedText(getString(R.string.Load_Data_Failed_str))
                                */
                                .closeSuccessAnim();
                        //.show()
                    }
                });
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
                        // 检查网络连接，如果无网络可用，就不需要进行连网操作等
                        NetworkInfo info = manager.getActiveNetworkInfo();
                        if (info == null || !manager.getBackgroundDataSetting()) {
                            Toast.makeText(context, context.getString(R.string.networkConnectionFailed), Toast.LENGTH_SHORT).show();
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    ld.loadFailed();
                                }
                            });
                            return;
                        }
                        JSONObject root = new JSONObject();
                        try {
                            root.put("UserNo", Long.parseLong(GUserNum));
                            root.put("DetectionDateStart", "2017-04-21");
                            root.put("DetectionDateEnd", "2017-04-21");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        JSONObject out = GlobalHelper.PostData(root, "http://120.77.255.57/ting/getUserData.php");
                        if (out == null) {
                            Toast.makeText(context, context.getString(R.string.networkConnectionFailed), Toast.LENGTH_SHORT).show();
                            return;
                        }
                        System.out.println(out);
                        SharedPreferences.Editor editor = sp.edit();
                        try {
                            if (!out.isNull("UserNickname")) {
                                NickName = out.get("UserNickname").toString();
                                editor.putString("NickName", NickName);
                            }
                            if (!out.isNull("Age")) {
                                Age = out.getInt("Age");
                                editor.putInt("Age", Age);
                            }
                            if (!out.isNull("StartDay")) {
                                FirstDay = out.get("StartDay").toString();
                                editor.putString("FirstDay", FirstDay);
                            }
                            if (!out.isNull("Menstruation")) {
                                Menstruation = out.getInt("Menstruation");
                                editor.putInt("Menstruation", Menstruation);
                            }
                            if (!out.isNull("PeriodLength")) {
                                PeriodLength = out.getInt("PeriodLength");
                                editor.putInt("PeriodLength", PeriodLength);
                            }
                            if (!out.isNull("Sex")) {
                                Sex = out.getInt("Sex");
                                editor.putInt("Sex", Sex);
                            }
                            if (!out.isNull("AssociatedUser")) {
                                AssociatedUser = out.getString("AssociatedUser");
                                editor.putString("AssociatedUser", AssociatedUser);
                            }
                            editor.apply();
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    if (ld != null)
                                        ld.loadSuccess();
                                    if (NickName.isEmpty() || ((Age == 0 || FirstDay.isEmpty() || Menstruation == 0 || PeriodLength == 0)&&Sex==0))
                                        CompletePersonalInfo();
                                    if(Sex == 1)
                                    {
                                        finish();
                                        Intent intent = new Intent("manMainActivity");
                                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                        startActivity(intent);
                                    }
                                }
                            });
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        }
        if (BleHandler == null) {
            BleHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    switch (msg.what) {
                        case 0:
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    BleDisconnCountDown = BleBeatsSpan;
                                    bleManager.writeDevice(
                                            GlobalHelper.CYUUID_SERVICE.toString(),
                                            GlobalHelper.CYUUID_TX.toString(),
                                            "CMD_ON".getBytes(),mBleCharacterCallback);

                                }
                            });
                            break;
                        case 1:
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    bleManager.writeDevice(
                                            GlobalHelper.CYUUID_SERVICE.toString(),
                                            GlobalHelper.CYUUID_TX.toString(),
                                            "CMD_OFF".getBytes(),mBleCharacterCallback);
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            BleOpDelay(500);
                                            handler.post(new Runnable() {
                                                @Override
                                                public void run() {
                                                    System.out.println("Ble检测完成的断开");
                                                    bleManager.closeBluetoothGatt();
                                                    new Thread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            BleOpDelay(500);
                                                            bleManager = null;
                                                        }
                                                    });
                                                }
                                            });
                                        }
                                    }).start();
                                }

                            });
                            break;
                        case 2:
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    //bleManager.closeBluetoothGatt();
                                }
                            });
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            break;
                        case 3:
                            isBleConnectingOrConnected = bleManager.isConnectingOrConnected();
                            break;
                        default:
                            break;
                    }
                }
            };
        }

//        setContentView(layout);

    }


    //是否请求位置权限
    private boolean mayRequestLocation() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        if (checkSelfPermission(ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        if (shouldShowRequestPermissionRationale(ACCESS_FINE_LOCATION)) {/*
            Snackbar.make(this, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
                    .setAction(android.R.string.ok, new View.OnClickListener() {
                        @Override
                        @TargetApi(Build.VERSION_CODES.M)
                        public void onClick(View v) {
                            requestPermissions(new String[]{ACCESS_FINE_LOCATION}, REQUEST_FINE_LOCATION);
                        }
                    });
*/
            bleManager.enableBluetooth();
            if (!bleManager.isInScanning())
            {
                bleManager.scanNamesAndConnect(new String[]{"Nordic_Chen","Nordic_Temp"}, BleScanTime, true, BleCallback);
            }
            //bleManager.scanNameAndConnect("Nordic_Chen", BleScanTime, true, BleCallback);
            ResetDetecting();
        } else {
            //请求权限
            requestPermissions(new String[]{ACCESS_FINE_LOCATION}, REQUEST_FINE_LOCATION);
        }
        return false;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_FINE_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // The requested permission is granted.

                    bleManager.enableBluetooth();
                    if (!bleManager.isInScanning()){
                        bleManager.scanNamesAndConnect(new String[]{"Nordic_Chen","Nordic_Temp"}, BleScanTime, true, BleCallback);
                    }
                    //bleManager.scanNameAndConnect("Nordic_Chen", BleScanTime, true, BleCallback);
                    ResetDetecting();
                } else {
                    // The user disallowed the requested permission.
                }
            }
        }
    }


    public void onClickDetectionHistory(View view) {
        Intent intent = new Intent("detectionHistoryActivity");
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
//        finish();
    }
    public void onClickDetectionTemperature(View view) {
        Intent intent = new Intent("temperatureActivity");
//        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    public void onClickUser(View view) {
        Intent intent = new Intent("ImprovePersonalInformationActivity");
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
//        finish();
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @SuppressLint("ResourceAsColor")
    public void onClickDetection(View view) {
        UploadRawDetectionData = 0;
        if(!GUserNum.isEmpty()) {
            new Thread(UpdateOp).start();
        }
        ResetDetecting();
        //overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
        isBleConnectingOrConnected = true;
        //非实验时启动检测

        Intent i = new Intent("DetectingActivity");
        startActivity(i);
        RelativeLayout ConnectingRelativeLayout = (RelativeLayout) findViewById(R.id.ConnectingRelativeLayout);
        ConnectingRelativeLayout.setVisibility(View.GONE);
        RelativeLayout ChooseModeRelativeLayout = (RelativeLayout) findViewById(R.id.ChooseModeRelativeLayout);
        ChooseModeRelativeLayout.setVisibility(View.VISIBLE);
        textView5.setText(R.string.selectDetectionMode);

        /* 用于实验时录入数据*/

        if (!DetectionType.equals("")) {

            pvRawDetectionData = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int option2, int options3, View v) {
                    //返回的分别是三个级别的选中位置
                    //String tx = cardItem.get(options1).getPickerViewText();
                    //btn_CustomOptions.setText(tx);
                }
            })
                    .setLayoutRes(R.layout.pickerview_custom_raw_detection_data_options, new CustomListener() {
                        @Override
                        public void customLayout(View v) {
                            final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                            ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                            final EditText etRawDetectionData = (EditText)v.findViewById(R.id.etDialogRawDetectionData);
                            tvSubmit.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    UploadRawDetectionData = Double.parseDouble(etRawDetectionData.getText().toString());
                                    new Thread(UpdateOp).start();
                                    pvRawDetectionData.returnData();
                                    pvRawDetectionData.dismiss();
                                    ResetDetecting();
                                    //overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
                                    isBleConnectingOrConnected = true;
                                    Intent i = new Intent("DetectingActivity");
                                    startActivity(i);
                                    RelativeLayout ConnectingRelativeLayout = (RelativeLayout) findViewById(R.id.ConnectingRelativeLayout);
                                    ConnectingRelativeLayout.setVisibility(View.GONE);
                                    RelativeLayout ChooseModeRelativeLayout = (RelativeLayout) findViewById(R.id.ChooseModeRelativeLayout);
                                    ChooseModeRelativeLayout.setVisibility(View.VISIBLE);
                                    textView5.setText(R.string.selectDetectionMode);
                                }
                            });

                            ivCancel.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    pvNickName.dismiss();
                                }
                            });

                        }
                    })
                    .isDialog(true)
                    .build();
            pvRawDetectionData.setPicker(new ArrayList<>());//添加数据
            /*pvRawDetectionData.show();*/


        } else {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), context.getString(R.string.selectDetectionMode),
                            Toast.LENGTH_SHORT).show();
                }
            });
        }/**/
    }


    public void onInputPersonalConfirm(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                NickName = etNickName.getText().toString();
                FirstDay = etFirstDay.getText().toString();
                LastDay = etLastDay.getText().toString();
                if (!etAge.getText().toString().isEmpty()) {
                    Age = Integer.parseInt(etAge.getText().toString());
                }
                if (!etMenstruation.getText().toString().isEmpty()) {
                    Menstruation = Integer.parseInt(etMenstruation.getText().toString());
                }
                JSONObject root = new JSONObject();
                try {
                    root.put("UserNo", Long.parseLong(GUserNum));/*Long.parseLong("18817833425")*/
                    if (!NickName.isEmpty()) {
                        root.put("UserNickname", NickName);
                    }
                    if (Age != 0) {
                        root.put("Age", Age);
                    }
                    if (!FirstDay.isEmpty()) {
                        root.put("StartDay", FirstDay);
                    }
                    if (!LastDay.isEmpty()) {
                        root.put("EndDay", LastDay);
                    }
                    if (Menstruation != 0) {
                        root.put("Menstruation", Menstruation);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                JSONObject out = GlobalHelper.PostData(root, "http://120.77.255.57/ting/updateUser.php");
                System.out.println(out.toString());
                String tempstr = null;
                try {
                    tempstr = out.get("OperateResult").toString();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                final String Resultcode = tempstr;
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (Resultcode != null && Resultcode.compareTo("1") >= 0) {
                            Toast.makeText(getApplicationContext(), context.getString(R.string.modifySuccessfully),
                                    Toast.LENGTH_SHORT).show();
                            RelativeLayout that = (RelativeLayout) findViewById(R.id.InputPersonalInformationRelativeLayout);
                            that.setVisibility(View.GONE);
                        } else {
                            Toast.makeText(getApplicationContext(), context.getString(R.string.modifyUnsuccessfully),
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }).start();
    }

    public void onClickConnect(View view) {
        if (DEBUG_MODE)
            Connect();
    }

    public void ReStartThis(View view) {
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

    public void Connect() {
        if(DeviceName.compareTo("Nordic_Chen")!=0){
            //温度计
            Intent intent = new Intent("temperatureActivity");
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        else {
            System.out.println("Ble:连接蓝牙后的UI更新前");
            final RelativeLayout ConnectingRelativeLayout = (RelativeLayout) findViewById(R.id.ConnectingRelativeLayout);
            final RelativeLayout ChooseModeRelativeLayout = (RelativeLayout) findViewById(R.id.ChooseModeRelativeLayout);

            handler.post(new Runnable() {
                @RequiresApi(api = Build.VERSION_CODES.M)
                @SuppressLint("ResourceAsColor")
                @Override
                public void run() {
                    System.out.println("Ble:连接蓝牙后的UI更新");

                    RelativeLayout rlCCAni = (RelativeLayout) findViewById(R.id.rlCCAni);

                    if (rlCCAni != null && rlCCAni.getVisibility() == View.VISIBLE) {
                        rlCCAni.setVisibility(View.GONE);
                        FrameLayout flGuideBtn = (FrameLayout) findViewById(R.id.flGuideBtn);
                        Button btnGuide = (Button) findViewById(R.id.btnGuide);
                        FrameLayout flAniMode1 = (FrameLayout) findViewById(R.id.flAniMode1);
                        Button btnAniMode1 = (Button) findViewById(R.id.btnAniMode1);
                        FrameLayout flAniMode2 = (FrameLayout) findViewById(R.id.flAniMode2);
                        Button btnAniMode2 = (Button) findViewById(R.id.btnAniMode2);

                        rlCCAni.clearAnimation();

                        flGuideBtn.setAlpha(1);
                        flAniMode1.setAlpha(0);
                        flAniMode2.setAlpha(0);
                        btnGuide.setAlpha(1);
                        btnGuide.setEnabled(true);
                        btnAniMode1.setEnabled(false);
                        btnAniMode1.setAlpha(0);
                        flAniMode1.setTranslationX(0);
                        btnAniMode2.setEnabled(false);
                        btnAniMode2.setAlpha(0);
                        flAniMode2.setTranslationX(0);


                        if (playingGuideAniSet != null && playingGuideAniSet.isRunning()) {
                            //playingGuideAniSet.end();
                            playingGuideAniSet.end();
                            playingGuideAniSet.cancel();
                            playingGuideAniSet = null;
                            System.out.println("Ani Stop");
                        }
                    }

                    if (ConnectingRelativeLayout != null)
                        ConnectingRelativeLayout.setVisibility(View.GONE);

                    if (ChooseModeRelativeLayout != null)
                        ChooseModeRelativeLayout.setVisibility(View.VISIBLE);
                    textView5.setText(R.string.selectDetectionMode);
                    //Toast.makeText(context, "蓝牙已连接", Toast.LENGTH_SHORT).show();

                }
            });
        }
    }

    public void Disconnect() {
        System.out.println("Ble:断开蓝牙后的UI更新前");
        handler.post(new Runnable() {
            @Override
            public void run() {
                System.out.println("Ble:断开蓝牙后的UI更新");
                RelativeLayout ConnectingRelativeLayout = (RelativeLayout) findViewById(R.id.ConnectingRelativeLayout);
                if (ConnectingRelativeLayout != null)
                    ConnectingRelativeLayout.setVisibility(View.VISIBLE);
                RelativeLayout ChooseModeRelativeLayout = (RelativeLayout) findViewById(R.id.ChooseModeRelativeLayout);
                if (ChooseModeRelativeLayout != null)
                    ChooseModeRelativeLayout.setVisibility(View.GONE);
                //Toast.makeText(context, "蓝牙已连接", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void onClickBack(View view) {
        finish();
    }

    public void onClickSkip(View view) {
        RelativeLayout ConnectingRelativeLayout = (RelativeLayout) findViewById(R.id.ConnectingRelativeLayout);
        ConnectingRelativeLayout.setVisibility(View.VISIBLE);
        RelativeLayout rlCCAni = (RelativeLayout) findViewById(R.id.rlCCAni);
        rlCCAni.setVisibility(View.GONE);
        FrameLayout flGuideBtn = (FrameLayout) findViewById(R.id.flGuideBtn);
        Button btnGuide = (Button) findViewById(R.id.btnGuide);
        FrameLayout flAniMode1 = (FrameLayout) findViewById(R.id.flAniMode1);
        Button btnAniMode1 = (Button) findViewById(R.id.btnAniMode1);
        FrameLayout flAniMode2 = (FrameLayout) findViewById(R.id.flAniMode2);
        Button btnAniMode2 = (Button) findViewById(R.id.btnAniMode2);

        rlCCAni.clearAnimation();

        flGuideBtn.setAlpha(1);
        flAniMode1.setAlpha(0);
        flAniMode2.setAlpha(0);
        btnGuide.setAlpha(1);
        btnGuide.setEnabled(true);
        btnAniMode1.setEnabled(false);
        btnAniMode1.setAlpha(0);
        flAniMode1.setTranslationX(0);
        btnAniMode2.setEnabled(false);
        btnAniMode2.setAlpha(0);
        flAniMode2.setTranslationX(0);


        if (playingGuideAniSet != null && playingGuideAniSet.isRunning()) {
            //playingGuideAniSet.end();
            playingGuideAniSet.end();
            playingGuideAniSet.cancel();
            playingGuideAniSet = null;
            System.out.println("Ani Stop");
        }

        /*
        if(!PlayedGuide)
            BleInit();
        PlayedGuide=true;
        */
    }

    void AniInit() {
        int aniDuration = 500;
        final FrameLayout flGuideBtn = (FrameLayout) findViewById(R.id.flGuideBtn);
        final Button btnGuide = (Button) findViewById(R.id.btnGuide);
        FrameLayout flAniMode1 = (FrameLayout) findViewById(R.id.flAniMode1);
        final Button btnAniMode1 = (Button) findViewById(R.id.btnAniMode1);
        FrameLayout flAniMode2 = (FrameLayout) findViewById(R.id.flAniMode2);
        final Button btnAniMode2 = (Button) findViewById(R.id.btnAniMode2);
        guideAniSet = new AnimatorSet();
        if (guideAniSet.isRunning())
            return;
        ObjectAnimator flGuideBtnOut = ObjectAnimator.ofFloat(flGuideBtn, "alpha", 1f, 0f).setDuration(aniDuration);
        ObjectAnimator btnGuideOut = ObjectAnimator.ofFloat(btnGuide, "alpha", 1f, 0f).setDuration(aniDuration / 2);
        ObjectAnimator flAniMode1In = ObjectAnimator.ofFloat(flAniMode1, "alpha", 0f, 1f).setDuration(aniDuration);
        ObjectAnimator flAniMode2In = ObjectAnimator.ofFloat(flAniMode2, "alpha", 0f, 1f).setDuration(aniDuration);

        ObjectAnimator flAniMode1Lift = ObjectAnimator.ofFloat(flAniMode1, "translationX", 0, -35 * density).setDuration(aniDuration);
        ObjectAnimator flAniMode2Right = ObjectAnimator.ofFloat(flAniMode2, "translationX", 0, 35 * density).setDuration(aniDuration);

        ObjectAnimator btnAniMode1In = ObjectAnimator.ofFloat(btnAniMode1, "alpha", 0f, 1f).setDuration((long) (aniDuration / 1.25));
        ObjectAnimator btnAniMode2In = ObjectAnimator.ofFloat(btnAniMode2, "alpha", 0f, 1f).setDuration((long) (aniDuration / 1.25));


        guideAniSet.play(flGuideBtnOut).with(btnGuideOut).with(flAniMode1In).with(flAniMode2In);
        guideAniSet.play(flAniMode1Lift).with(flAniMode2Right).after(flGuideBtnOut).after(aniDuration);
        guideAniSet.play(btnAniMode1In).with(btnAniMode2In).after(flAniMode1Lift).after(aniDuration);
        guideAniSet.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                btnGuide.setEnabled(false);
                btnAniMode1.setEnabled(true);
                btnAniMode2.setEnabled(true);
            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }
        });
    }

    public void onClickPlayGuide(View view) {
        /*//旧版
        RelativeLayout ConnectingRelativeLayout = (RelativeLayout) findViewById(R.id.ConnectingRelativeLayout);
        ConnectingRelativeLayout.setVisibility(View.GONE);
        RelativeLayout rlCCAni = (RelativeLayout) findViewById(R.id.rlCCAni);
        rlCCAni.setVisibility(View.VISIBLE);
        if(!set.isRunning())
            set.start();
        if(!set2.isRunning())
            set2.start();
       */

        AniInit();
        guideAniSet.start();

        if (!isGuideAniInit) {
            GuideAniInit();
            isGuideAniInit = true;
        }
    }

    public void onClickAniMode1(View view) {

        AniMode = 1;
        RelativeLayout ConnectingRelativeLayout = (RelativeLayout) findViewById(R.id.ConnectingRelativeLayout);
        ConnectingRelativeLayout.setVisibility(View.GONE);
        RelativeLayout rlCCAni = (RelativeLayout) findViewById(R.id.rlCCAni);
        rlCCAni.setVisibility(View.VISIBLE);
        RelativeLayout rlAni1 = (RelativeLayout) findViewById(R.id.rlAni1);
        RelativeLayout rlAni2 = (RelativeLayout) findViewById(R.id.rlAni2);
        rlAni1.setVisibility(View.VISIBLE);
        rlAni2.setVisibility(View.GONE);
        rlCCAni.clearAnimation();
        playingGuideAniSet = set;
        playingGuideAniSet.start();

    }

    public void onClickAniMode2(View view) {
        if (!isGuideAniInit) {
            GuideAniInit();
            isGuideAniInit = true;
        }
        AniInit();
        AniMode = 2;
        RelativeLayout ConnectingRelativeLayout = (RelativeLayout) findViewById(R.id.ConnectingRelativeLayout);
        ConnectingRelativeLayout.setVisibility(View.GONE);
        RelativeLayout rlCCAni = (RelativeLayout) findViewById(R.id.rlCCAni);
        rlCCAni.setVisibility(View.VISIBLE);
        RelativeLayout rlAni1 = (RelativeLayout) findViewById(R.id.rlAni1);
        RelativeLayout rlAni2 = (RelativeLayout) findViewById(R.id.rlAni2);
        rlAni2.setVisibility(View.VISIBLE);
        rlAni1.setVisibility(View.GONE);
        rlCCAni.clearAnimation();
        playingGuideAniSet = set2;
        playingGuideAniSet.start();
    }

//    public void onClickHCG(View view) {
//        if (set3 != null && set4 != null)
//            if (set3.isRunning() || set4.isRunning())
//                return;
//        Button hcgButton = (Button) findViewById(R.id.button18);
//        Button lhButton = (Button) findViewById(R.id.button19);
//        //hcgButton.setBackground(ContextCompat.getDrawable(context,R.drawable.quickscanshape_cw));
//        //hcgButton.setBackground(ContextCompat.getDrawable(context,R.drawable.control_center_circle));
//        //hcgButton.setTextColor(ContextCompat.getColor(context,R.color.signup_pink));
//        //hcgButton.setTextColor(getResources().getColor(R.color.H_pink));
//        lhButton.setBackground(ContextCompat.getDrawable(context, R.drawable.quickscanshape_o_with_shadow_new));
//        lhButton.setTextColor(ContextCompat.getColor(context, white));
//        DetectionType = "HCG";
//        DHV1.StartDraw();
//        DHV2.ClearDraw();
//
//        FrameLayout flLHb = (FrameLayout) findViewById(R.id.flLHb);
//        set3 = new AnimatorSet();
//        ObjectAnimator flLHbSmallX = ObjectAnimator.ofFloat(flLHb, "scaleX", 1f, 0f).setDuration(200);
//        ObjectAnimator flLHbSmallY = ObjectAnimator.ofFloat(flLHb, "scaleY", 1f, 0f).setDuration(200);
//        set3.play(flLHbSmallX).with(flLHbSmallY);
//        if (flLHb.getScaleX() == 1 && flLHb.getScaleY() == 1)
//            set3.start();
//
//        FrameLayout flHCGb = (FrameLayout) findViewById(R.id.flHCGb);
//        set4 = new AnimatorSet();
//        ObjectAnimator flHCGbBigX = ObjectAnimator.ofFloat(flHCGb, "scaleX", 0.f, 1.f).setDuration(200);
//        ObjectAnimator flHCGbBigY = ObjectAnimator.ofFloat(flHCGb, "scaleY", 0.f, 1.f).setDuration(200);
//        set4.play(flHCGbBigX).with(flHCGbBigY);
//        if (flHCGb.getScaleX() == 0 && flHCGb.getScaleY() == 0)
//            set4.start();
//    }
//
//    public void onClickLH(View view) {
//        if (set3 != null && set4 != null)
//            if (set3.isRunning() || set4.isRunning())
//                return;
//        Button lhButton = (Button) findViewById(R.id.button19);
//        Button hcgButton = (Button) findViewById(R.id.button18);
//        lhButton.setBackground(ContextCompat.getDrawable(context, R.drawable.quickscanshape_o_with_shadow_new));
//        lhButton.setTextColor(ContextCompat.getColor(context, white));
//        DetectionType = "LH";
//        DHV2.StartDraw();
//        DHV1.ClearDraw();
//
//        FrameLayout flLHb = (FrameLayout) findViewById(R.id.flLHb);
//        set3 = new AnimatorSet();
//        ObjectAnimator flLHbBigX = ObjectAnimator.ofFloat(flLHb, "scaleX", 0f, 1f).setDuration(200);
//        ObjectAnimator flLHbBigY = ObjectAnimator.ofFloat(flLHb, "scaleY", 0f, 1f).setDuration(200);
//        set3.play(flLHbBigX).with(flLHbBigY);
//        if (flLHb.getScaleX() == 0 && flLHb.getScaleY() == 0)
//            set3.start();
//
//        FrameLayout flHCGb = (FrameLayout) findViewById(R.id.flHCGb);
//        set4 = new AnimatorSet();
//        ObjectAnimator flHCGbSmallX = ObjectAnimator.ofFloat(flHCGb, "scaleX", 1.f, 0.f).setDuration(200);
//        ObjectAnimator flHCGbSmallY = ObjectAnimator.ofFloat(flHCGb, "scaleY", 1.f, 0.f).setDuration(200);
//        set4.play(flHCGbSmallX).with(flHCGbSmallY);
//        if (flHCGb.getScaleX() == 1 && flHCGb.getScaleY() == 1)
//            set4.start();
//    }

    /*
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[],@NonNull  int[] grantResults) {
            switch_view (requestCode) {
                case PERMISSION_REQUEST_COARSE_LOCATION:
                    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        System.out.println("Ble权限申请成功");
                    }
                    break;
            }
        }
        */

    public void findService(BluetoothGatt gatt) {

        List<BluetoothGattService> gattServices = gatt.getServices();

        System.out.println("Ble GATT服务总数:" + gattServices.size());
        for (BluetoothGattService gattService : gattServices) {
            System.out.println("Ble GATT服务 UUID ：" + gattService.getUuid().toString());
            //System.out.println("Ble UUID_SERVICE "+UUID_SERVICE.toString());
            //判断是否是指定的服务
            if (gattService.getUuid().toString().equalsIgnoreCase(UUID_SERVICE.toString())) {
                //获取参数
                List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
                System.out.println("Ble 参数总数:" + gattCharacteristics.size());
                for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
                    //判断是否是指定的通知
                    System.out.println("Ble Character UUID ：" + gattCharacteristic.getUuid().toString());
                    //System.out.println("Ble UUID_NOTIFY :"+UUID_NOTIFY.toString());
                    if (gattCharacteristic.getUuid().toString().equalsIgnoreCase(UUID_RX.toString())) {
                        //保存配置
                        rxCharacteristic = gattCharacteristic;
                        //订阅配置
                        mBleService.setCharacteristicNotification(rxCharacteristic, true);
                        //return;
                    } else if (gattCharacteristic.getUuid().toString().equalsIgnoreCase(UUID_TX.toString())) {
                        txCharacteristic = gattCharacteristic;
                        //mBleService.setCharacteristicNotification(gattCharacteristic, true);
                        //return;

                    }
                }
                CYConn = false;
            } else if (gattService.getUuid().toString().equalsIgnoreCase(CYUUID_SERVICE.toString())) {
                //获取参数
                List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
                System.out.println("Ble 参数总数:" + gattCharacteristics.size());
                if (gattCharacteristics.size() != 0)
                    for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
                        //判断是否是指定的通知
                        System.out.println("Ble Character UUID ：" + gattCharacteristic.getUuid().toString());
                        //System.out.println("Ble UUID_NOTIFY :"+UUID_NOTIFY.toString());
                        if (gattCharacteristic.getUuid().toString().equalsIgnoreCase(CYUUID_RX.toString())) {
                            //保存配置
                            rxCharacteristic = gattCharacteristic;
                            //订阅配置
                            mBleService.setCharacteristicNotification(rxCharacteristic, true);
                            //return;
                        } else if (gattCharacteristic.getUuid().toString().equalsIgnoreCase(CYUUID_TX.toString())) {
                            txCharacteristic = gattCharacteristic;
                            //mBleService.setCharacteristicNotification(gattCharacteristic, true);
                            //return;
                        }
                    }
                else {

                    //mBleService.close();
                    //mBleService=null;
                    //gatt.disconnect();
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent = getIntent();
                            intent.setFlags(FLAG_ACTIVITY_CLEAR_TOP);
                            finish();
                            startActivity(intent);
                            //Toast.makeText(context, "蓝牙正在重新连接", Toast.LENGTH_SHORT).show();

                        }
                    });
                }
                CYConn = true;
            }
        }


        Thread readData = new Thread(new Runnable() {
            @Override
            public void run() {
                while (mBleService != null && mBleService.getConnectDevices() != null && mBleService.getConnectDevices().size() > 0) {
                    System.out.println("Ble 已连接设备数:" + mBleService.getConnectDevices().size());
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                /*
                if (mBleService!=null)
                    mBleService.close();
                */
            }
        });
        readData.start();

    }

    public void BleInit() {
        BleData[0] = 0;
        BleData[1] = 0;
        BleR = 0;
        BleG = 0;
        BleB = 0;
        ShowAD = false;
        ShowRGB = false;

        mNeedRescan = true;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // Android M Permission check
            if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
            }
        }

        serviceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                mIsBind = true;
                mBleService = ((BleService.LocalBinder) service).getService();
                //Ble初始化操作
                if (mBleService.initialize()) {
                    //打开蓝牙
                    if (!mBleService.isEnableBluetooth()) {

                        mBleService.enableBluetooth(true);



                    }
                    mBleService.setOnDataAvailableListener(new BleService.OnDataAvailableListener() {
                        @Override
                        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
                            //处理特性读取返回的数据
                            System.out.println("Ble特性读取返回:" + characteristic.getStringValue(0));
                        }

                        @Override
                        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
                            //处理通知返回的数据
                            int v = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0);
                            ReadCount++;
                            System.out.println("Ble通知原始第" + ReadCount + "个返回:" + v);
                            ShowRGB = false;
                            ShowAD = false;
                            if (CYConn) {
                                BleBuffer[BleReadCount] = v;
                                if (BleReadCount == 7 && BleBuffer[0] == 255 && BleBuffer[1] == 1 && BleBuffer[2] == 8) {
                                    int temp = BleBuffer[3];
                                    temp = temp << 8;
                                    //AD1=BleBuffer[3];

                                    AD1 = BleBuffer[4] + temp;

                                    temp = BleBuffer[5];
                                    temp = temp << 8;
                                    AD2 = BleBuffer[6] + temp;
                                    //AD2=BleBuffer[5];
                                    ShowAD = true;
                                    BleReadCount = -1;

                                } else if (BleReadCount == 7 && BleBuffer[0] == 255 && BleBuffer[1] == 0 && BleBuffer[2] == 8) {
                                    BleData[0] = BleBuffer[3];
                                    BleR = BleBuffer[5];
                                    BleG = BleBuffer[6];
                                    BleB = BleBuffer[7];
                                    BleReadCount = -1;
                                } else if (BleReadCount >= 7) {
                                    BleReadCount = -1;
                                }
                                if (BleReadCount == 0 && BleBuffer[0] != 255)
                                    BleReadCount--;

                                BleReadCount++;


//                                if (v == 255 && BleReadCount == 0) {
//                                    BleReadCount = 1;
//                                } else if (v == 0 && BleReadCount == 1) {
//                                    BleReadCount = 2;
//                                } else if (v == 8 && BleReadCount == 2) {
//                                    BleReadCount = 3;
//                                } else if (v >= 0 && v <= 255 && BleReadCount == 3) {
//                                    BleReadCount = 4;
//                                    BleData[0] = v;
//                                    System.out.println("Ble AD:"+ v);
//                                }else if (v >= 0 && v <= 255 && BleReadCount == 4) {
//                                    BleReadCount = 5;
//                                }else if (v >= 0 && v <= 255 && BleReadCount == 5) {
//                                    BleReadCount = 6;
//                                    BleR = v;
//                                    System.out.println("Ble R:"+ v);
//                                }else if (v >= 0 && v <= 255 && BleReadCount == 6) {
//                                    BleReadCount = 7;
//                                    BleG = v;
//                                    System.out.println("Ble G:"+ v);
//                                } else if (v >= 0 && v <= 255 && BleReadCount == 7) {
//                                    BleReadCount = 0;
//                                    BleB = v;
//                                    System.out.println("Ble B:"+ v);
//
//                                    /*
//                                    Message message = Message.obtain();
//                                    message.what = 0;
//                                    Bundle bundle = new Bundle();
//                                    bundle.putIntArray("BleData", BleData);
//                                    message.setData(bundle);
//                                    if (BleHandler != null)
//                                        BleHandler.sendMessage(message);
//                                        */
//                                    //System.out.println("Ble通知返回:" + Arrays.toString(BleData));
//                                }
                            } else {
                                final byte[] data = characteristic.getValue();
                                if (data.length >= 8) {
                                    System.out.println("Ble通知bytes返回" + Arrays.toString(characteristic.getValue()));
                                    if (characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0) == 76 &&
                                            characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 1) == 86 &&
                                            characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 2) == 65 &&
                                            characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 5) == 66
                                            ) {
                                        ShowAD = true;
                                        int AD11 = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 3);
                                        AD11 = AD11 << 8;
                                        int AD12 = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 4);
                                        AD1 = AD11 + AD12;
                                        AD1 /= 10;
                                        System.out.println("Ble通知AD1返回:" + AD1);
                                        int AD21 = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 6);
                                        AD21 = AD21 << 8;
                                        int AD22 = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 7);
                                        AD2 = AD21 + AD22;
                                        AD2 /= 10;
                                        System.out.println("Ble通知AD2返回:" + AD2);
                                    } else {
                                        ShowRGB = true;
                                        int R1 = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 1);
                                        R1 = R1 << 8;
                                        int R2 = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 2);
                                        BleR = R1 + R2;
                                        //BleR*=0.004800/2;
                                        System.out.println("Ble通知R返回:" + BleR);
                                        int G1 = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 4);
                                        G1 = G1 << 8;
                                        int G2 = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 5);
                                        BleG = G1 + G2;
                                        //BleG*=0.005065/2;
                                        System.out.println("Ble通知G返回:" + BleG);
                                        int B1 = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 7);
                                        B1 = B1 << 8;
                                        int B2 = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 8);
                                        BleB = B1 + B2;
                                        //BleB*=0.004104/2;
                                        System.out.println("Ble通知B返回:" + BleB);
                                    }
                                }
                            }

                        }

                        @Override
                        public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
                            System.out.println("BleDescriptorRead返回:" + Arrays.toString(descriptor.getValue()));
                        }
                    });
                    mBleService.setOnServicesDiscoveredListener(new BleService.OnServicesDiscoveredListener() {
                        @Override
                        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
                            System.out.println("Ble状态 " + status);
                            if (status == BluetoothGatt.GATT_SUCCESS) {
                                //查找服务
                                findService(gatt);
                            } else {
                                if (gatt.getDevice().getUuids() == null) {
                                    System.out.println("Ble获取uuid失败");
                                }
                            }
                        }
                    });
                    mBleService.setOnConnectListener(new BleService.OnConnectionStateChangeListener() {
                        @Override
                        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
                            if (gatt.getDevice().getName() != null)
                                System.out.println("Ble设备:" + gatt.getDevice().getName());
                            if (newState == BluetoothProfile.STATE_DISCONNECTED) {

                                System.out.println("Ble连接已断开");
                                System.out.println("Ble关闭:");
                                mBleService.enableBluetooth(false);
                                System.out.println("Ble启动:");
                                if (mBleService.enableBluetooth(true)) {
                                    do {
                                        {/*等待蓝牙开启*/}
                                    } while (!mBleService.isEnableBluetooth());
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            try {
                                                Thread.sleep(500);
                                            } catch (InterruptedException e) {
                                                e.printStackTrace();
                                            }
                                            mBleService.scanLeDevice(true);
                                            System.out.println("开始扫描Ble设备");
                                        }
                                    });
                                }
                                //gatt.disconnect();
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        /*
                                        RelativeLayout rlCC = (RelativeLayout)findViewById(R.id.ConnectFailRelativeLayout);
                                        if (rlCC!=null){
                                            rlCC.setVisibility(View.VISIBLE);
                                        }
                                        */
                                        //unbindService(serviceConnection);
                                        /*
                                        try {
                                            Thread.sleep(50);
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                        Intent intent = getIntent();
                                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                        finish();
                                        startActivity(intent);
*/
                                        //Toast.makeText(context, "蓝牙正在重新连接", Toast.LENGTH_SHORT).show();
                                    }
                                });

                                //Ble连接已断开
                            } else if (newState == BluetoothProfile.STATE_CONNECTING) {
                                System.out.println("Ble正在连接");
                                //Ble正在连接
                            } else if (newState == BluetoothProfile.STATE_CONNECTED) {
                                System.out.println("Ble已连接");
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        Connect();
                                    }
                                });
                                //Ble已连接
                            } else if (newState == BluetoothProfile.STATE_DISCONNECTING) {
                                System.out.println("Ble正在断开连接");
                                //Ble正在断开连接
                            }
                        }
                    });
                    if (mBleService.enableBluetooth(true)) {
                        //Ble扫描回调
                        mBleService.setOnLeScanListener(new BleService.OnLeScanListener() {
                            @Override
                            public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
                                //每当扫描到一个Ble设备时就会返回，（扫描结果重复的库中已处理）
                                if (device != null && device.getName() != null &&
                                        (device.getName().compareTo("Nordic_Temp") == 0 ||
                                                device.getName().compareTo("Nordic_Chen") == 0)
                                        ) {
                                    mBleService.scanLeDevice(false);
                                    mNeedRescan = false;
                                    System.out.println("停止扫描Ble设备");
                                    System.out.println("Ble设备：" + device.getName() + ",Address:" + device.getAddress());
                                    System.out.println("Ble设备类型：" + device.getBluetoothClass().getMajorDeviceClass());

                                    mBleService.connect(device.getAddress());
                                    String strTemp = new String(scanRecord, Charset.forName("GBK"));
                                    System.out.println("Ble设备scanRecord：" + strTemp);
                                    /*
                                    if (!strTemp.isEmpty()){
                                        String usefulData = strTemp.substring(86,106);
                                        String strPower = usefulData.substring(6,8);
                                        int intPower = Integer.parseInt(strPower, 16);
                                        System.out.println("Ble设备电量：" + intPower);
                                    }*/
                                }
                            }
                        });


                        do {
                            {/*等待蓝牙开启*/}
                        } while (!mBleService.isEnableBluetooth());
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Thread.sleep(500);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                mBleService.scanLeDevice(true);
                                System.out.println("开始扫描Ble设备");
                                Thread reScan = new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        while (mBleService != null && mNeedRescan) {
                                            if (scanCount >= 10) {
                                                System.out.println("Ble rescan");
                                                mBleService.scanLeDevice(false);
                                                try {
                                                    Thread.sleep(1000);
                                                } catch (InterruptedException e) {
                                                    e.printStackTrace();
                                                }
                                                mBleService.scanLeDevice(true);
                                                scanCount = 0;
                                            }

                                            scanCount++;
                                            try {
                                                Thread.sleep(1000);
                                            } catch (InterruptedException e) {
                                                e.printStackTrace();
                                            }
                                        }
                /*
                if (mBleService!=null)
                    mBleService.close();
                */
                                    }
                                });
                                //handler.post(reScan);
                            }
                        });
                    }
                    //Toast.makeText(getApplicationContext(), "蓝牙已打开", Toast.LENGTH_SHORT).show();
                } else {
                    //Toast.makeText(getApplicationContext(), "不支持蓝牙", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                mBleService.disconnect();
                unbindService(serviceConnection);
                //mBleService = null;
                //mIsBind = false;
            }
        };
        Intent serviceIntent = new Intent(this, BleService.class);
        System.out.println("Ble Start Bind:");

        bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
        mIsTimeUnbide = true;


    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && GUserNum.equals("")) {
            Intent intent = new Intent("MainActivity");
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        } else if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return false;
    }

    public void ResetDetecting() {
        ReadCount = 0;
        AD1 = 0;
        AD2 = 0;
        AD1List.clear();
        AD2List.clear();
        NewestDetectDataCount = 0;
    }

    public void setNotify() {
        bleManager.notify(
                GlobalHelper.CYUUID_SERVICE.toString(),
                GlobalHelper.CYUUID_RX.toString(),
                new BleCharacterCallback() {
                    @Override
                    public void onSuccess(BluetoothGattCharacteristic characteristic) {
                        ReadCount++;
                        System.out.println("Ble第" + BleReadCount + "次读到数据" + characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0));
                        BleBuffer[BleReadCount] = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0);
                        if (BleReadCount == 7 && BleBuffer[0] == 255 && BleBuffer[1] == 1 && BleBuffer[2] == 8) {
                            long temp = BleBuffer[3];
                            temp = temp << 8;
                            //AD1=BleBuffer[3];
                            AD1 = BleBuffer[4] + (int)temp;
                            temp = BleBuffer[5];
                            temp = temp << 8;
                            AD2 = BleBuffer[6] + (int)temp;
                            BleReadCount = -1;
                            if(TemperatureDetect){
                                double AD= (AD1 / 1024.0) * 1.2 * 3;
                                Temperature = (AD - 2.728) / 0.044;
                                System.out.println("Ble读到温度:" + Temperature+",AD:"+AD+",AD1:"+AD1);
                                final int ad1 = AD1;
                                final double F_temperature = Temperature;
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(context, "收到原始数据AD1:" + ad1 + ",温度:" + F_temperature, Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }else {
                                //AD2=BleBuffer[5];
                                ShowAD = true;
                                BatteryValue = BleBuffer[7];
                                if (AD1 < 1010 && AD2 < 1010) {
                                    AD2 -= 50;
                                }
                                if (DEBUG_MODE_SHOW_TOAST_AD) {
                                    final int ad1 = AD1, ad2 = AD2;
                                    AD1List.add(AD1);
                                    AD2List.add(AD2);
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(context, "收到原始数据AD1:" + ad1 + ",AD2:" + ad2, Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                }
                                int Correction = 0;
                                int Correction2 = 0;
                                if (BleAddress.compareTo("C9:CD:B9:3B:03:75") == 0)//8
                                {
                                    DNum = 8;
                                    System.out.println("Ble 8号机");
                                    Correction = 0;
                                    Correction2 = 0;
                                } else if (BleAddress.compareTo("DE:9A:22:70:56:A0") == 0)//4
                                {
                                    DNum = 4;
                                    System.out.println("Ble 4号机");
                                    Correction = 122;
                                    Correction2 = 57;
                                } else if (BleAddress.compareTo("C1:2F:AE:6E:72:65") == 0)//5
                                {
                                    DNum = 5;
                                    System.out.println("Ble 5号机");
                                    Correction = 93;
                                    Correction2 = 50;
                                } else if (BleAddress.compareTo("E4:86:FE:3F:D1:47") == 0)//2
                                {
                                    DNum = 2;
                                    System.out.println("Ble 2号机");
                                    Correction = 0;
                                } else if (BleAddress.compareTo("CD:E0:BB:DB:47:D0") == 0)//n2
                                {
                                    DNum = -2;
                                    System.out.println("Ble 新2号机");
                                    Correction = -20;
                                } else if (BleAddress.compareTo("DE:BD:C0:89:ED:E0") == 0)//1
                                {
                                    DNum = 1;
                                    System.out.println("Ble 1号机");
                                    Correction = 65;
                                    Correction2 = 320;
                                } else if (BleAddress.compareTo("D7:FE:28:50:00:C8") == 0)//9
                                {
                                    DNum = 9;
                                    System.out.println("Ble 9号机");
                                    Correction = 440;
                                    Correction2 = 320;
                                } else if (BleAddress.compareTo("DF:BB:1E:77:E9:7D") == 0)//w
                                {
                                    DNum = 0;
                                    System.out.println("Ble 白号机");
                                    Correction = 145;
                                    Correction2 = -180;
                                } else if (BleAddress.compareTo("CD:A6:E0:99:B6:57") == 0)//nw
                                {
                                    DNum = -1;
                                    System.out.println("Ble 新白号机");
                                    Correction = 5;
                                    Correction2 = -230;
                                }
                                AD1 += Correction;
                                AD2 += Correction2;
                                ADRecord.add(AD1);
                                ADRecord.add(AD2);
                                System.out.println("Ble读到数据AD1:" + AD1 + "  AD2:" + AD2);
                                BleDisconnCountDown = BleBeatsSpan;
                                if (Mode == 1)
                                    NewestDetectDataBuffer[NewestDetectDataCount % NewestDetectDataBufferSize] = AD1 * 1.0f / AD2;
                                else {
                                    NewestDetectDataBuffer[NewestDetectDataCount % NewestDetectDataBufferSize] = AD1;
                                    NewestDetectDataBufferTwo[NewestDetectDataCount % NewestDetectDataBufferTwoSize] = AD2;
                                }
                            }
                            NewestDetectDataCount++;
                        }
                        BleReadCount++;
                    }

                    @Override
                    public void onFailure(BleException exception) {
                        System.out.println("Ble读取数据失败" + exception.toString());
                        if (exception.getCode() == 102) {

                            if (bleManager != null) {
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        //bleManager.closeBluetoothGatt();
                                    }
                                });

                                try {
                                    Thread.sleep(500);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                //bleManager = null;
                                //bleManager = new BleManager(context);

                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        bleManager.enableBluetooth();

                                        if (!bleManager.isInScanning())
                                        {
                                            bleManager.scanNamesAndConnect(new String[]{"Nordic_Chen","Nordic_Temp"}, BleScanTime, true, BleCallback);
                                        }
                                        //bleManager.scanNameAndConnect("Nordic_Chen", BleScanTime, true, BleCallback);
                                    }
                                });
                                ResetDetecting();
                            }
                        }
                    }

                    @Override
                    public void onInitiatedResult(boolean result) {
                        System.out.println("Ble读取数据结果" + result);
                        /*失败重试
                        if (!result) {
                            try {
                                Thread.sleep(200);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            setNotify();
                        }
                        */
                    }
                }
        );
    }

    private void GuideAniInit() {


        TextView tvAni1 = (TextView) findViewById(R.id.tvAni1);
        TextView tvAni2 = (TextView) findViewById(R.id.tvAni2);
        TextView tvAni3 = (TextView) findViewById(R.id.tvAni3);
        TextView tvAni4 = (TextView) findViewById(R.id.tvAni4);
        TextView tvAni5 = (TextView) findViewById(R.id.tvAni5);
        TextView tvAni1t = (TextView) findViewById(R.id.tvAni1t);
        TextView tvAni2t = (TextView) findViewById(R.id.tvAni2t);
        TextView tvAni3t = (TextView) findViewById(R.id.tvAni3t);
        TextView tvAni4t = (TextView) findViewById(R.id.tvAni4t);
        TextView tvAni5t = (TextView) findViewById(R.id.tvAni5t);

        TextView tvAni21 = (TextView) findViewById(R.id.tvAni21);
        TextView tvAni22 = (TextView) findViewById(R.id.tvAni22);
        TextView tvAni23 = (TextView) findViewById(R.id.tvAni23);
        TextView tvAni24 = (TextView) findViewById(R.id.tvAni24);
        TextView tvAni25 = (TextView) findViewById(R.id.tvAni25);
        TextView tvAni21t = (TextView) findViewById(R.id.tvAni21t);
        TextView tvAni22t = (TextView) findViewById(R.id.tvAni22t);
        TextView tvAni23t = (TextView) findViewById(R.id.tvAni23t);
        TextView tvAni24t = (TextView) findViewById(R.id.tvAni24t);
        TextView tvAni25t = (TextView) findViewById(R.id.tvAni25t);
        int aniDuration = 1000;
        set = new AnimatorSet();
        set2 = new AnimatorSet();
        /*
        ObjectAnimator pic1In =ObjectAnimator.ofFloat(ivAniPic1,"alpha",0f,1f).setDuration(aniDuration);
        ObjectAnimator pic1Out =ObjectAnimator.ofFloat(ivAniPic1,"alpha",1f,0f).setDuration(aniDuration);
        ObjectAnimator pic2In =ObjectAnimator.ofFloat(ivAniPic2,"alpha",0f,1f).setDuration(aniDuration);
        ObjectAnimator pic2Out =ObjectAnimator.ofFloat(ivAniPic2,"alpha",1f,0f).setDuration(aniDuration);
        ObjectAnimator pic3In =ObjectAnimator.ofFloat(ivAniPic3,"alpha",0f,1f).setDuration(aniDuration);
        ObjectAnimator pic3Out =ObjectAnimator.ofFloat(ivAniPic3,"alpha",1f,0f).setDuration(aniDuration);
        ObjectAnimator pic4In =ObjectAnimator.ofFloat(ivAniPic4,"alpha",0f,1f).setDuration(aniDuration);
        ObjectAnimator pic4Out =ObjectAnimator.ofFloat(ivAniPic4,"alpha",1f,0f).setDuration(aniDuration);

        ObjectAnimator txt1In =ObjectAnimator.ofFloat(tvAni1,"alpha",0f,1f).setDuration(aniDuration);
        ObjectAnimator txt1Out =ObjectAnimator.ofFloat(tvAni1,"alpha",1f,0f).setDuration(aniDuration);
        ObjectAnimator txt2In =ObjectAnimator.ofFloat(tvAni2,"alpha",0f,1f).setDuration(aniDuration);
        ObjectAnimator txt2Out =ObjectAnimator.ofFloat(tvAni2,"alpha",1f,0f).setDuration(aniDuration);
        ObjectAnimator txt3In =ObjectAnimator.ofFloat(tvAni3,"alpha",0f,1f).setDuration(aniDuration);
        ObjectAnimator txt3Out =ObjectAnimator.ofFloat(tvAni3,"alpha",1f,0f).setDuration(aniDuration);
        ObjectAnimator txt4In =ObjectAnimator.ofFloat(tvAni4,"alpha",0f,1f).setDuration(aniDuration);
        ObjectAnimator txt4Out =ObjectAnimator.ofFloat(tvAni4,"alpha",1f,0f).setDuration(aniDuration);

        int timeSpan = 3000;
        set.play(pic1In).with(txt1In);
        set.play(pic1Out).with(pic2In).with(txt1Out).with(txt2In).after(pic1In).after(timeSpan);
        set.play(pic2Out).with(pic3In).with(txt2Out).with(txt3In).after(pic2In).after(2*timeSpan);
        set.play(pic3Out).with(pic4In).with(txt3Out).with(txt4In).after(pic3In).after(3*timeSpan);
        set.play(pic4Out).with(txt4Out).after(pic4In).after(4*timeSpan);
*/
        //ImageView iv = (ImageView) findViewById(R.id.anilist);
        //FAD = FrameByFrameAnimationDrawable.loadAnimation(context, R.drawable.animlist, true);
        //iv.setImageDrawable(FAD);
        ImageView iv2 = (ImageView) findViewById(R.id.anilist2);
        FAD2 = FrameByFrameAnimationDrawable.loadAnimation(context, R.drawable.animlist2, true);
        iv2.setImageDrawable(FAD2);

        ObjectAnimator txt1In = ObjectAnimator.ofFloat(tvAni1, "alpha", 0f, 1f).setDuration(aniDuration);
        ObjectAnimator txt1Out = ObjectAnimator.ofFloat(tvAni1, "alpha", 1f, 0f).setDuration(aniDuration);
        ObjectAnimator txt2In = ObjectAnimator.ofFloat(tvAni2, "alpha", 0f, 1f).setDuration(aniDuration);
        ObjectAnimator txt2Out = ObjectAnimator.ofFloat(tvAni2, "alpha", 1f, 0f).setDuration(aniDuration);
        ObjectAnimator txt3In = ObjectAnimator.ofFloat(tvAni3, "alpha", 0f, 1f).setDuration(aniDuration);
        ObjectAnimator txt3Out = ObjectAnimator.ofFloat(tvAni3, "alpha", 1f, 0f).setDuration(aniDuration);
        ObjectAnimator txt4In = ObjectAnimator.ofFloat(tvAni4, "alpha", 0f, 1f).setDuration(aniDuration);
        ObjectAnimator txt4Out = ObjectAnimator.ofFloat(tvAni4, "alpha", 1f, 0f).setDuration(aniDuration);
        ObjectAnimator txt5In = ObjectAnimator.ofFloat(tvAni5, "alpha", 0f, 1f).setDuration(aniDuration);
        ObjectAnimator txt5Out = ObjectAnimator.ofFloat(tvAni5, "alpha", 1f, 0f).setDuration(aniDuration);
        ObjectAnimator txt1tIn = ObjectAnimator.ofFloat(tvAni1t, "alpha", 0f, 1f).setDuration(aniDuration);
        ObjectAnimator txt1tOut = ObjectAnimator.ofFloat(tvAni1t, "alpha", 1f, 0f).setDuration(aniDuration);
        ObjectAnimator txt2tIn = ObjectAnimator.ofFloat(tvAni2t, "alpha", 0f, 1f).setDuration(aniDuration);
        ObjectAnimator txt2tOut = ObjectAnimator.ofFloat(tvAni2t, "alpha", 1f, 0f).setDuration(aniDuration);
        ObjectAnimator txt3tIn = ObjectAnimator.ofFloat(tvAni3t, "alpha", 0f, 1f).setDuration(aniDuration);
        ObjectAnimator txt3tOut = ObjectAnimator.ofFloat(tvAni3t, "alpha", 1f, 0f).setDuration(aniDuration);
        ObjectAnimator txt4tIn = ObjectAnimator.ofFloat(tvAni4t, "alpha", 0f, 1f).setDuration(aniDuration);
        ObjectAnimator txt4tOut = ObjectAnimator.ofFloat(tvAni4t, "alpha", 1f, 0f).setDuration(aniDuration);
        ObjectAnimator txt5tIn = ObjectAnimator.ofFloat(tvAni5t, "alpha", 0f, 1f).setDuration(aniDuration);
        ObjectAnimator txt5tOut = ObjectAnimator.ofFloat(tvAni5t, "alpha", 1f, 0f).setDuration(aniDuration);

        ObjectAnimator txt21In = ObjectAnimator.ofFloat(tvAni21, "alpha", 0f, 1f).setDuration(aniDuration);
        ObjectAnimator txt21Out = ObjectAnimator.ofFloat(tvAni21, "alpha", 1f, 0f).setDuration(aniDuration);
        ObjectAnimator txt22In = ObjectAnimator.ofFloat(tvAni22, "alpha", 0f, 1f).setDuration(aniDuration);
        ObjectAnimator txt22Out = ObjectAnimator.ofFloat(tvAni22, "alpha", 1f, 0f).setDuration(aniDuration);
        ObjectAnimator txt23In = ObjectAnimator.ofFloat(tvAni23, "alpha", 0f, 1f).setDuration(aniDuration);
        ObjectAnimator txt23Out = ObjectAnimator.ofFloat(tvAni23, "alpha", 1f, 0f).setDuration(aniDuration);
        ObjectAnimator txt24In = ObjectAnimator.ofFloat(tvAni24, "alpha", 0f, 1f).setDuration(aniDuration);
        ObjectAnimator txt24Out = ObjectAnimator.ofFloat(tvAni24, "alpha", 1f, 0f).setDuration(aniDuration);
        ObjectAnimator txt25In = ObjectAnimator.ofFloat(tvAni25, "alpha", 0f, 1f).setDuration(aniDuration);
        ObjectAnimator txt25Out = ObjectAnimator.ofFloat(tvAni25, "alpha", 1f, 0f).setDuration(aniDuration);
        ObjectAnimator txt21tIn = ObjectAnimator.ofFloat(tvAni21t, "alpha", 0f, 1f).setDuration(aniDuration);
        ObjectAnimator txt21tOut = ObjectAnimator.ofFloat(tvAni21t, "alpha", 1f, 0f).setDuration(aniDuration);
        ObjectAnimator txt22tIn = ObjectAnimator.ofFloat(tvAni22t, "alpha", 0f, 1f).setDuration(aniDuration);
        ObjectAnimator txt22tOut = ObjectAnimator.ofFloat(tvAni22t, "alpha", 1f, 0f).setDuration(aniDuration);
        ObjectAnimator txt23tIn = ObjectAnimator.ofFloat(tvAni23t, "alpha", 0f, 1f).setDuration(aniDuration);
        ObjectAnimator txt23tOut = ObjectAnimator.ofFloat(tvAni23t, "alpha", 1f, 0f).setDuration(aniDuration);
        ObjectAnimator txt24tIn = ObjectAnimator.ofFloat(tvAni24t, "alpha", 0f, 1f).setDuration(aniDuration);
        ObjectAnimator txt24tOut = ObjectAnimator.ofFloat(tvAni24t, "alpha", 1f, 0f).setDuration(aniDuration);
        ObjectAnimator txt25tIn = ObjectAnimator.ofFloat(tvAni25t, "alpha", 0f, 1f).setDuration(aniDuration);
        ObjectAnimator txt25tOut = ObjectAnimator.ofFloat(tvAni25t, "alpha", 1f, 0f).setDuration(aniDuration);

        int timeSpan = 3000;
        set.play(txt1In).with(txt1tIn);
        set.play(txt1Out).with(txt2In).with(txt1tOut).with(txt2tIn).after(txt1In).after(3400);
        set.play(txt2Out).with(txt3In).with(txt2tOut).with(txt3tIn).after(txt2In).after(11400);
        set.play(txt3Out).with(txt4In).with(txt3tOut).with(txt4tIn).after(txt3In).after(16400);
        set.play(txt4Out).with(txt5In).with(txt4tOut).with(txt5tIn).after(txt4In).after(22200);
        set.play(txt5Out).with(txt5tOut).after(txt5In).after(28800);
        set.setStartDelay(500);
        //set.start();
        set.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                IsFirstTimePlayAni = false;
                SharedPreferences.Editor editor = sp.edit();
                editor.putBoolean("IsFirstTimePlayAni", IsFirstTimePlayAni);
                editor.apply();
                ImageView iv = (ImageView) findViewById(R.id.anilist);
                FAD = FrameByFrameAnimationDrawable.loadAnimation(context, R.drawable.animlist, true);
                iv.setImageDrawable(FAD);
                FAD.start();
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                IsFirstTimePlayAni = false;
                SharedPreferences.Editor editor = sp.edit();
                editor.putBoolean("IsFirstTimePlayAni", IsFirstTimePlayAni);
                editor.apply();
                FAD.stop();
                //animation.setStartDelay(4000);
                animation.start();
            }
            @Override
            public void onAnimationCancel(Animator animation) {
                animation.cancel();
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }
        });

        set2.play(txt21In).with(txt21tIn);
        set2.play(txt21Out).with(txt22In).with(txt21tOut).with(txt22tIn).after(txt21In).after(3400);
        set2.play(txt22Out).with(txt23In).with(txt22tOut).with(txt23tIn).after(txt22In).after(11850);
        set2.play(txt23Out).with(txt24In).with(txt23tOut).with(txt24tIn).after(txt23In).after(15350);
        set2.play(txt24Out).with(txt25In).with(txt24tOut).with(txt25tIn).after(txt24In).after(20750);
        set2.play(txt25Out).with(txt25tOut).after(txt25In).after(25700);
        set2.setStartDelay(500);
        //set2.start();
        set2.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                IsFirstTimePlayAni = false;
                SharedPreferences.Editor editor = sp.edit();
                editor.putBoolean("IsFirstTimePlayAni", IsFirstTimePlayAni);
                editor.apply();
                ImageView iv2 = (ImageView) findViewById(R.id.anilist2);
                FAD2 = FrameByFrameAnimationDrawable.loadAnimation(context, R.drawable.animlist2, true);
                iv2.setImageDrawable(FAD2);
                FAD2.start();
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                IsFirstTimePlayAni = false;
                SharedPreferences.Editor editor = sp.edit();
                editor.putBoolean("IsFirstTimePlayAni", IsFirstTimePlayAni);
                editor.apply();
                FAD2.stop();
                //animation.setStartDelay(4000);
                animation.start();

            }

            @Override
            public void onAnimationCancel(Animator animation) {
                animation.cancel();
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }
        });


/*
        FAImageView faImageView1 = (FAImageView)findViewById(R.id.faimageview1);
        faImageView1.setInterval(100);
        faImageView1.setLoop(true);
        //faImageView1.addImageFrame(R.drawable.anipic0001);
        //faImageView1.addImageFrame(R.drawable.anipic0002);
        //faImageView1.addImageFrame(R.drawable.anipic0003);
        for (int i=1;i<162;i++){
            System.out.println("com.feijia.ting:id"+String.format("anipic%04d",i));
            faImageView1.addImageFrame(context.getResources().getIdentifier(String.format("anipic%04d",i),"drawable",context.getPackageName()));
        }

        faImageView1.startAnimation();
*//*
        final String FRAME_NAME = "anipic";
        List<String> frameList = null;
        try {
            final String[] frames = getAssets().list(FRAME_NAME);
            if (null != frames) {
                frameList = Arrays.asList(frames);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (null != frameList) {
            Collections.sort(frameList, new Comparator<String>() {

                private final String MATCH_FRAME_NUM = String.format("(?<=%s_).*(?=.png)", FRAME_NAME);
                private final Pattern p = Pattern.compile(MATCH_FRAME_NUM);

                @Override
                public int compare(String lhs, String rhs) {
                    try {
                        final Matcher lhsMatcher = p.matcher(lhs);
                        final Matcher rhsMatcher = p.matcher(rhs);
                        if (lhsMatcher.find()
                                && rhsMatcher.find()) {
                            return Integer.valueOf(lhsMatcher.group()) - Integer.valueOf(rhsMatcher.group());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return 0;
                }
            });

            List<FrameDrawable> frameDrawables = new ArrayList<>();
            for (String framePath : frameList) {
                Log.v("fileName",FRAME_NAME + "/" + framePath);
                FrameDrawable frameDrawable = new FrameDrawable(FRAME_NAME + "/" + framePath, 100);
                frameDrawables.add(frameDrawable);
            }
            FrameAnimationView mFrameAnimationView = (FrameAnimationView) findViewById(R.id.frame_animation);
            mFrameAnimationView.addFrameDrawable(frameDrawables);
            mFrameAnimationView.setOneShot(false);
            mFrameAnimationView.addFrameDrawable(frameDrawables);
            mFrameAnimationView.start();

        }*/
    }

    void ResetBleAndRescan() {
//重新初始化蓝牙并扫描
        System.out.println("isBleRescanThreadRunning:" + isBleRescanThreadRunning);
        if (false && !isBleRescanThreadRunning) {
            Thread bleRescanThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    while (isBleRescanThreadRunning) {

                        if (bleManager != null && bleManager.isConnectingOrConnected()) {
                            isBleRescanThreadRunning = false;
                            break;
                        }
                        System.out.println("Resetting Ble");

                        //bleManager.closeBluetoothGatt();
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        //bleManager = null;
                        //bleManager = new BleManager(context);

                        bleManager.enableBluetooth();
                        if (!bleManager.isInScanning())
                            bleManager.scanNameAndConnect("Nordic_Chen", BleScanTime, true, BleCallback);
                        ResetDetecting();
                        try {
                            Thread.sleep(5000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
            isBleRescanThreadRunning = true;
            bleRescanThread.start();
        }
    }

    void BleOpDelay(int time) {
        if (time <= 0)
            time = 100;
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    void BleOpDelay() {
        BleOpDelay(0);
    }

    void CompletePersonalInfo() {
        CompleteWelcome();
    }

    void CompleteWelcome() {
        pvWelcome = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                //String tx = cardItem.get(options1).getPickerViewText();
                //btn_CustomOptions.setText(tx);
                CompleteNickNameInfo();
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_welcome_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        final EditText etDialogNickName = (EditText) v.findViewById(R.id.etDialogNickName);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvWelcome.returnData();
                                pvWelcome.dismiss();
                            }
                        });

                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                //pvNetOut.dismiss();
                            }
                        });

                    }
                })
                .isDialog(true)
                .setOutSideCancelable(false)
                .build();
        pvWelcome.setPicker(new ArrayList<>());//添加数据
        pvWelcome.show();
    }


    void CompleteNickNameInfo() {
        pvNickName = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                //String tx = cardItem.get(options1).getPickerViewText();
                //btn_CustomOptions.setText(tx);
                CompleteNickChooseSex();
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        final EditText etDialogNickName = (EditText) v.findViewById(R.id.etDialogNickName);
                        etDialogNickName.setText(NickName);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                NickName = etDialogNickName.getText().toString();
                                //new Thread(UpdateOp).start();
                                pvNickName.returnData();
                                pvNickName.dismiss();

                            }
                        });

                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvNickName.dismiss();
                            }
                        });

                    }
                })
                .isDialog(true)
                .setOutSideCancelable(false)
                .build();
        pvNickName.setPicker(new ArrayList<>());//添加数据
        pvNickName.show();
    }

    void CompleteNickChooseSex()
    {
        pvChooseSex= new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                //String tx = cardItem.get(options1).getPickerViewText();
                //btn_CustomOptions.setText(tx);
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_sex_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        final CheckBox cbMale = (CheckBox)v.findViewById(R.id.cbMale);
                        final CheckBox cbFemale = (CheckBox)v.findViewById(R.id.cbFemale);
                        cbMale.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                cbFemale.setChecked(false);
                            }
                        });
                        cbFemale.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                cbMale.setChecked(false);
                            }
                        });
                        final EditText etDialogNickName = (EditText) v.findViewById(R.id.etDialogNickName);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if(cbFemale.isChecked()&&!cbMale.isChecked())
                                {
                                    //girl;
                                    Sex = 0;
                                    CompleteAgeInfo();
                                } else if(!cbFemale.isChecked()&&cbMale.isChecked())
                                {
                                    //boy;
                                    Sex = 1;
                                    new Thread(UpdateOp).start();
                                    finish();
                                    Intent intent = new Intent("manMainActivity");
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                    startActivity(intent);
                                } else {
                                    return;
                                }
                                pvChooseSex.returnData();
                                pvChooseSex.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                //pvNetOut.dismiss();
                            }
                        });

                    }
                })
                .isDialog(true)
                .setOutSideCancelable(false)
                .build();
        pvChooseSex.setPicker(new ArrayList<>());//添加数据
        pvChooseSex.show();
    }
    /*旧版选择性别
    void CompleteNickChooseSex()
    {
        pvChooseSex= new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                //String tx = cardItem.get(options1).getPickerViewText();
                //btn_CustomOptions.setText(tx);
                CompleteNickNameInfo();
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_choose_sex_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        final EditText etDialogNickName = (EditText) v.findViewById(R.id.etDialogNickName);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvChooseSex.returnData();
                                pvChooseSex.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                //pvNetOut.dismiss();
                            }
                        });

                    }
                })
                .isDialog(true)
                .setOutSideCancelable(false)
                .build();
        pvChooseSex.setPicker(new ArrayList<>());//添加数据
        pvChooseSex.show();
    }
    */

    void CompleteAgeInfo() {
        final int StartAge = 14;
        pvAge = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                Age = StartAge + options1;
                CompleteMenstruationInfo();
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_age_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvAge.returnData();
                                pvAge.dismiss();
                            }
                        });

                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvAge.dismiss();
                            }
                        });
                    }
                })
                .setContentTextSize(36)
                .isDialog(true)
                .setOutSideCancelable(false)
                .setBgColor(0xEEEEEE)
                .build();
        pvAge.setPicker(new ArrayList<String>() {
            {
                for (int i = StartAge; i < 81; i++) {
                    add("" + i);
                }
            }
        });
        pvAge.setSelectOptions(10);
        pvAge.show();
    }

    void CompleteMenstruationInfo() {
        final int StartMenstruation = 20;
        pvMenstruation = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                Menstruation = StartMenstruation + options1;
                CompleteFirstDayInfo();
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_menstruation_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvMenstruation.returnData();
                                pvMenstruation.dismiss();
                            }
                        });

                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvMenstruation.dismiss();
                            }
                        });
                    }
                })
                .setOutSideCancelable(false)
                .isDialog(true)
                .setContentTextSize(36)
                .setBgColor(0xEEEEEE)
                .build();
        pvMenstruation.setPicker(new ArrayList<String>() {
            {
                for (int i = StartMenstruation; i < 41; i++) {
                    add("" + i);
                }
            }
        });
        pvMenstruation.setSelectOptions(8);
        pvMenstruation.show();
    }

    void CompleteFirstDayInfo() {
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        //startDate.set(2013,1,1);
        Calendar endDate = Calendar.getInstance();
        //endDate.set(2020,1,1);

        //正确设置方式 原因：注意事项有说明
        startDate.set(2013, 0, 1);
        endDate.set(2020, 11, 31);
        pvFirstDay = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                FirstDay = format.format(date);
                CompletePeriodInfo();
            }
        }).setLayoutRes(R.layout.pickerview_custom_firstday_options, new CustomListener() {
            @Override
            public void customLayout(View v) {
                //自定义布局中的控件初始化及事件处理
                final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                tvSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvFirstDay.returnData();
                        pvFirstDay.dismiss();
                    }
                });
                ivCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvFirstDay.dismiss();
                    }
                });

            }
        })
                .setLabel("", "", "", "", "", "")
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .isCyclic(true)//是否循环滚动
                .setContentSize(24)
                .setOutSideCancelable(false)
                .setBgColor(0xEEEEEE)//滚轮背景颜色 Night mode
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(true)//是否显示为对话框样式
                .build();
        pvFirstDay.show();
    }

    void CompletePeriodInfo() {
        final int StartPeriod = 2;
        pvPeriod = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                CompleteWelcomeend();
                PeriodLength = StartPeriod + options1;
                new Thread(UpdateOp).start();
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_period_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvPeriod.returnData();
                                pvPeriod.dismiss();
                            }
                        });

                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvPeriod.dismiss();
                            }
                        });
                    }
                })
                .isDialog(true)
                .setOutSideCancelable(false)
                .setContentTextSize(36)
                .setBgColor(0xEEEEEE)
                .build();
        pvPeriod.setPicker(new ArrayList<String>() {
            {
                for (int i = StartPeriod; i < 8; i++) {
                    add("" + i);
                }
            }
        });
        pvPeriod.setSelectOptions(2);
        pvPeriod.show();
    }

    void CompleteWelcomeend() {
        pvWelcomeend = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

            }
        })
                .setLayoutRes(R.layout.pickerview_custom_welcomeend_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvWelcomeend.returnData();
                                pvWelcomeend.dismiss();

                            }
                        });

                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvWelcomeend.dismiss();
                            }
                        });
                    }
                })
                .isDialog(true)
                .setContentTextSize(36)
                .setBgColor(0xEEEEEE)
                .build();
        pvWelcomeend.setPicker(new ArrayList<String>() {
            {
            }
        });
        pvWelcomeend.setSelectOptions(2);
        pvWelcomeend.show();
    }

    public void onClickGotoPushPage(View view)
    {
        System.out.print("go to Push page");
        Intent intent = new Intent("PushPageActivity");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
    }

    @Override
    public void onItemClick(View view, int position, long id, String name) {
        DetectionType=name;
        tvStartDetection.setText(name);
    }

    @Override
    public void onItemSelected(View view, int position, long id, String name) {
        DetectionType=name;
        tvStartDetection.setText(name);
    }

    public void onClickShop(View view) {
        Intent intent = new Intent("ShoppingActivity");
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
//        finish();
    }
}
